package cn.enjoy.tool.juc;

import java.io.Serializable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author K
 * @date 2021/8/16 下午2:59
 */
public class CompletableFutureTest {
    private static ExecutorService executorService = Executors.newFixedThreadPool(4);


    public static void main(String[] args) throws ExecutionException, InterruptedException {

    handle();

    }


    /**
     * 处理
     */
    public static void handle() throws ExecutionException, InterruptedException {
        CompletableFuture<Object> completableFuture = CompletableFuture.supplyAsync(new Supplier<Object>() {
            @Override
            public Object get() {
                int i = 10 / 2;
                return i;
            }
        }, executorService);

        CompletableFuture<Object> handle = completableFuture.handle((result, throwable) -> {
            if (result != null) {
                return (int) result * 3;
            }
            if (throwable != null) {
                return throwable;
            }
            return null;
        });

        System.out.println(handle.get());

        // 这边也可以插入完成时回调
        CompletableFuture<Object> completableFuture1 = handle.whenCompleteAsync(new BiConsumer<Object, Throwable>() {
            @Override
            public void accept(Object o, Throwable throwable) {
                System.out.println("-------o=" + o.toString());
                System.out.println("-------throwable=" + throwable);
            }
        });
        executorService.shutdown();
    }

    /**
     * 回调
     */
    public static void callback() throws ExecutionException, InterruptedException {
        CompletableFuture<Object> completableFuture = CompletableFuture.supplyAsync(new Supplier<Object>() {
            @Override
            public Object get() {
                int i = 10 / 0;
                return i;
            }
        }, executorService);

        CompletableFuture<Object> completableFuture1 = completableFuture.whenComplete(new BiConsumer<Object, Throwable>() {
            @Override
            public void accept(Object o, Throwable throwable) {
                System.out.println("-------o=" + o.toString());
                System.out.println("-------throwable=" + throwable);
            }
        });

        CompletableFuture<Object> future = completableFuture1.exceptionally(new Function<Throwable, Object>() {
            @Override
            public Object apply(Throwable throwable) {
                System.out.println("throwable=" + throwable);
                return 123;
            }
        });

        System.out.println(future.get());
        System.out.println(completableFuture.get());
    }

}
